<template>
  <div class="chart" ref="main"></div>
</template>
<script>
import { expendNodes } from "./mock";
// 引入 ECharts 主模块
var echarts = require("echarts/lib/echarts");
// 引入柱状图
require("echarts/lib/chart/graph");
// 引入提示框和标题组件
require("echarts/lib/component/tooltip");
require("echarts/lib/component/title");
export default {
  name: "Charts",
  components: {},
  mixins: [],
  props: {
    chartList: {
      type: Array,
      required: true,
    },
  },
  watch: {
    chartList: {
      handler(val) {
        this.formatData(val || [], true);
      },
    },
  },
  data() {
    return {
      myChart: "",
      entityData: [],
      entityLinks: [],
      lastClickId: "",
      label2color: {
        作物: "#c77eb5",
        病害: "#7bbfea",
        虫害: "#ffd400",
        药物名: "#c05c7a",
        药物剂型: "#47a993",
        类别: "#b8e345",
      },
    };
  },
  computed: {},
  methods: {
    /**
     * 设置echarts配置项,重绘画布
     */
    initCharts() {
      if (!this.myChart) {
        this.myChart = echarts.init(this.$refs.main);
        this.myChart.on("click", (params) => {
          if (params.dataType === "node") {
            //判断点击的是图表的节点部分
            this.nodeClick(params);
          }
        });
      }

      // 指定图表的配置项和数据
      let option = {
        // 动画更新变化时间
        animationDurationUpdate: 2000,
        animationEasingUpdate: "quinticInOut",
        tooltip: {
          show: false,
        },
        series: [
          {
            // zoom: 1,
            type: "graph",
            layout: "force",
            legendHoverLink: true, //是否启用图例 hover(悬停) 时的联动高亮。
            hoverAnimation: true, //是否开启鼠标悬停节点的显示动画
            edgeLabel: {
              position: "middle", //边上的文字样式
              normal: {
                formatter: "{c}",
                show: true,
              },
            },
            edgeSymbol: ["arrow", ""],
            force: {
              edgeLength: [100, 200],
              repulsion: 30,
              gravity: 0.1,
              friction: 0.5,
            },
            roam: true,
            draggable: true, //每个节点的拖拉
            itemStyle: {
              normal: {
                color: function (param) {
                  if (param.data.color == undefined)
                    // console.log(param.data.color);
                    return "#9edfb8";
                  else return param.data.color;
                },
                cursor: "pointer",
                label: {
                  show: true,
                  position: [-10, -15],
                  textStyle: {
                    color: "black",
                    fontStyle: "normal",
                    fontWeight: "bold",
                    fontFamily: "sans-serif",
                    fontSize: 12,
                  },
                },
                nodeStyle: {
                  brushType: "both",
                  borderColor: "rgba(255,215,0,0.4)",
                  borderWidth: 1,
                },
              },
              emphasis: {
                shadowColor: "#00FAE1",
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowBlur: 40,
              },
            },
            lineStyle: {
              width: 2,
            },
            label: {
              color: "#00FAE1",
              fontSize: 18,
            },
            symbolSize: 18, //节点大小
            links: this.entityLinks,
            data: this.entityData,
            cursor: "pointer",
          },
        ],
      };
      // console.log("option", option)
      // 使用刚指定的配置项和数据显示图表。
      this.myChart.setOption(option);
    },
    /**
     * 格式化数据到表格需要的数据
     */
    async nodeClick(params) {
      const index = this.entityData.findIndex(
        (item) => item.id === params.data.id
      );
      const info = this.entityData[index];
      if (info.isRoot) return;
      if (!info.isClicked) {
        this.lastClickId = info.id;
        info.isClicked = true;
        this.entityData.splice(index, 1, info);
        let result = await expendNodes(info.id);
        this.formatData(result);
      } else {
        //已经点击过  当前点击需要折叠
        info.isClicked = false;
        this.entityData.splice(index, 1, info);
        this.removeChilds(info.id);
      }
    },
    formatData(list, reset = false) {
      let nodes = [];
      const entitydata = [];
      const entitylinks = [];
      let target = "";
      if (reset) {
        this.entityData = [];
        this.entityLinks = [];
        nodes = [].concat(list[0].children);
        target = list[0].id + "";
        list[0]["color"] = this.label2color[list[0]["label"]];
        const dataInfo = {
          id: target,
          name: list[0].name,
          category: list[0].label,
          color: list[0].color,
          isClicked: true,
          isRoot: true,
          symbolSize: 30,
        };
        entitydata.push(dataInfo);
      } else {
        nodes = [].concat(list);
        target = this.lastClickId;
      }

      nodes.forEach((item, index) => {
        // 注意 id必须是string  否则连线连不上
        const id = item.id + "";
        item.color = this.label2color[item["relationship"]];
        const dataInfo = {
          id: id,
          parentId: target,
          category: item.label,
          name: item.name,
          color: item.color,
          isClicked: false,
        };
        entitydata.push(dataInfo);
        if (target != item.id) {
          entitylinks.push({
            value: item.label,
            target: target,
            source: id,
          });
        }
      });
      this.entityData.push(...entitydata);
      this.entityLinks.push(...entitylinks);

      this.initCharts();
    },
    /**
     * 点击节点折叠操作
     */
    removeChilds(id) {
      // 清除data数据
      let list = [];
      let links = [];
      let delIds = [];
      this.getDeleteParentIds(delIds, [id]);

      this.entityData.map((item) => {
        if (!delIds.includes(item.id)) {
          list.push(item);
        }
      });
      this.entityLinks.map((item) => {
        if (!delIds.includes(item.source) && !delIds.includes(item.target)) {
          links.push(item);
        }
      });
      this.entityData = [].concat(list);
      this.entityLinks = [].concat(links);
      this.initCharts();
    },
    /**
     * 递归获取当前节点以下节点id
     */
    getDeleteParentIds(delIds, ids) {
      let list = [];
      this.entityData.map((item) => {
        if (ids.includes(item.parentId)) {
          list.push(item.id);
        }
      });
      if (list.length > 0) {
        delIds.push(...list);
        this.getDeleteParentIds(delIds, list);
      }
    },
  },
};
</script>
<style scoped>
.chart {
  height: 650px;
}
body {
  margin: 0;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  height: 100vh;
}
</style>